# !/usr/local/bin/python3
# -*- encoding: utf-8 -*-
# @FileName :   Spider.py
# @DateTime :   2022/8/25 | 11:29
# @Author   :   IoTus3
# @GitHub   :   https://gitee.com/IoTus3
# @Contact  :   xianglin.fu3@gmail.com
# @License  :   (C)Copyright 2022-2023, LinYuStudio-NLPR-CASIA
# @Editor   :   Power by PyCharm
# @Desc     :   爬虫类-爬取商品数据


# 导入相关库
from bs4 import BeautifulSoup

# 引入Wares对象
from src.main.models.Wares import *
from src.main.models.CommonTypes import *


# 爬虫类
class AmazonSpider(object):
    __host = "https://www.amazon.cn/"
    __host_asin_tpl = "{}{}".format(__host, "dp/")
    # __host_task_list_tpl = "{}{}".format(__host, "gp/offer-listing")

    def __init__(self, asin):
        self.__host = AmazonSpider.__host
        self.__host_asin_tpl = AmazonSpider.__host_asin_tpl
        # self.__host_task_list_tpl = AmazonSpider.__host_task_list_tpl
        self.asin = asin

    def run(self):
        """
        开始爬虫
        :return: wares data
        """
        # 爬虫的目标url
        target_url = "{}{}/".format(self.__host_asin_tpl, self.asin)
        # 返回的对象
        resp = send_request(target_url)
        # 页面内容
        content = BeautifulSoup(resp.text, "html.parser")
        # 标题
        title = content.find("span", attrs={"id": "productTitle"}).text.strip()
        # url
        url = target_url
        # 价格
        price = content.find("span", attrs={"class": "a-price a-text-price a-size-medium apexPriceToPay"}).text.split(
            "¥")
        # 将price转换为浮点型
        price = float(price[1])
        # 创建一个wares对象
        wares = Wares(self.asin, title, url, price)
        # 返回一个wares的对象
        return wares, resp

